<template>
	<van-tabs class="app-mob-tree" v-model:active="activeTab" shrink animated>
		<template v-for="item in tabs" :key="item[valueKey]">
			<van-tab :title="getTabTitle(item)" :titleClass="getTabTitleClass(item)">
				<TreeOptions
					:multiple="multiple"
					:fieldNames="fieldNames"
					:options="item.options"
					:selections="selections"
					:selected="item.selected"
					@selectionChange="handSelectionChange"
				></TreeOptions>
			</van-tab>
		</template>
	</van-tabs>
</template>
<script setup lang="ts">
import TreeOptions from './components/tree-options.vue';
import { deepCopy, IParam } from '@/core';
import { treeProps, TreeTab } from './tree';
import { Ref } from 'vue';
const activeTab = ref(0);
const tabs = ref<TreeTab[]>([]);
const props = defineProps(treeProps);
const value = ref('');
const emit = defineEmits<{
	(name: 'selectionChange', selections: IParam[]): void;
	(name: 'valueChange', node: IParam): void;
}>();
let selections: Ref<IParam[]> = ref([]);
const {
	text: textKey,
	value: valueKey,
	children: childrenKey,
	leaf: leafKey,
} = props.fieldNames;

const getSelectedOptionsByValue = (
	options: any[],
	value: any
): any[] | undefined => {
	for (const option of options) {
		if (option[valueKey] === value) {
			return [option];
		}
		if (option[childrenKey]) {
			const selectedOptions = getSelectedOptionsByValue(
				option[childrenKey],
				value
			);
			if (selectedOptions) {
				return [option, ...selectedOptions];
			}
		}
	}
};
const updateTabs = (dataChange: boolean = false) => {
	const { items } = props;
	if (value.value !== undefined) {
		const selectedOptions = getSelectedOptionsByValue(items, value.value);
		if (selectedOptions) {
			let optionsCursor = items;
			let next: any = null;
			tabs.value = selectedOptions.map((option) => {
				const tab = {
					options: optionsCursor,
					selected: option,
				};
				next = optionsCursor.find(
					(item) => item[valueKey] === option[valueKey]
				);
				if (next) {
					optionsCursor = next[childrenKey];
				}
				return tab;
			});

			if (optionsCursor) {
				tabs.value.push({
					options: optionsCursor,
					selected: null,
				});
			}
			nextTick(() => {
				activeTab.value = tabs.value.length - 1;
			});
			return;
		}
	}
	tabs.value = [
		{
			options: props.items,
			selected: null,
		},
	];
    if (dataChange) {
        updateDefaultSelect()
    }
};

const updateDefaultSelect = (resetSelect: boolean = false) => {
    const { selectedKeys, items } = props;
    if (resetSelect) {
        selections.value = [];
    }
    if (selectedKeys && items && selectedKeys.length > 0 && items.length > 0) {
        const setDefaultSelect = (items: IParam[]) => {
            items.forEach((item: IParam) => {
                const selectedKey = selectedKeys.find((selectedKey: string) => {
                    return selectedKey == item[valueKey];
                })
                if (selectedKey) {
                    const index = selections.value.findIndex((selection: IParam) => {
                        return selectedKey == selection[valueKey];
                    })
                    if (index == -1) {
                        selections.value.push(item)
                    }
                }
                if (item[childrenKey] && item[childrenKey].length > 0) {
                    setDefaultSelect(item[childrenKey]);
                }
            })
        }
        setDefaultSelect(items);
    }
}

watch(() => props.items, () => updateTabs(true), { deep: true, immediate: true });
watch(() => props.selectedKeys, () => updateDefaultSelect(true), { deep: true, immediate: true });
// 节点选中
const onChange = ({ curSelectOptions }: any) => {
	if (!curSelectOptions) {
		return;
	}
	if (curSelectOptions[leafKey]) {
        updateTabs();
		emit('selectionChange', selections.value);
		return;
	}
    if (!props.load || curSelectOptions.isLoaded) {
        updateTabs();
    } else if (props.load && props.load instanceof Function) {
        props.load(curSelectOptions);
    }
};

const getTabTitle = (item: TreeTab): string => {
	return item.selected?.[textKey] || '请选择';
};
const getTabTitleClass = (item: any) => {
	const classNames = {
		'van-cascader__tab': true,
		'van-cascader__tab--unselected': !item.selected,
	};
	return classNames;
};

const handSelectionChange = (option: any) => {
	const tabIndex = activeTab.value;
	if (option[leafKey]) {
		if (props.multiple) {
			const selectItemIndex = selections.value?.findIndex((item: any) => {
				return item[valueKey] == option[valueKey];
			});
			if (selectItemIndex != undefined && selectItemIndex != -1) {
				selections.value.splice(selectItemIndex, 1);
			} else {
				selections.value.push(option);
			}
		} else {
			selections.value = [option];
		}
	} else {
		tabs.value[tabIndex].selected = option;
	}
	if (option[valueKey] && !option[leafKey]) {
		if (tabs.value.length > tabIndex + 1) {
			tabs.value = tabs.value.slice(0, tabIndex + 1);
		}
		const nextTab = {
			options: option[valueKey],
			selected: null,
		};

		if (tabs.value[tabIndex + 1]) {
			tabs.value[tabIndex + 1] = nextTab;
		} else {
			tabs.value.push(nextTab);
		}

		nextTick(() => {
			activeTab.value++;
		});
	}
	value.value = option[valueKey];
	const params = {
		value: option[valueKey],
		tabIndex,
		curSelectOptions: option,
	};
	onChange(params);
};
</script>
